import sys

import requests,json,os,re
import datetime,argparse
from time import sleep
import random
import logging
# 显示消息时间

print( '====================')
print('auther:ewaimp')
print('v1.1')
print('2023.4.20')
print('1,loging is done')
print( '====================')

class DataUpload():
    logging.basicConfig(filename='../vpsNode/wg.log', level=logging.INFO, format='%(asctime)s %(message)s',
                        datefmt='%m/%d/%Y %I:%M:%S')

    def __init__(self):
        logging.info('initing arg....')
        self.ip =''
        self.runConf = {"datas": []}
        self.data_path = '../vpsNode/data.txt'
        self.wgName ='wg-easy'
        self.sendData = {}
        self.header = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            "Content-Type": "application/json",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                          "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"
        }
        self.parser = argparse.ArgumentParser(description='demo first version v1.0')
        # 2. 添加命令行参数
        self.parser.add_argument('--interval', type=int, default=60, help='request data interval time')
        self.parser.add_argument('--dataPath', type=str, default='data.txt', help='data file path')
        self.parser.add_argument('--apiAddress', type=str, default='https://node.wontonsway.net/api/Node/notice',
                                 help='api address http://host:port/api')
        self.parser.add_argument('--template', type=str, default='wg.conf', help='general template conf file')
        self.parser.add_argument('--localData', type=str, default='false', help='local api test')
        self.parser.add_argument('--resetConf', type=str, default='false', help='reset config file')
        self.parser.add_argument('--scriptName', type=str, default='demon.sh', help='exec the script file')
        self.args = self.parser.parse_args()
        logging.info('current params...')
        logging.info(self.args)

    def getWanIP(self):
        # if self.args.virtualHost != 'yes':
        eth = self.getEth().strip()
        logging.info(f'get interface : {eth}')
        cmd = os.popen(f"ip a |grep {eth}" + "|awk '/inet/ {print $2}'")
        ips = cmd.readline()
        ip = ips.split('/')
        logging.info(f'node wan ip is :> {ip[0]}')
        return ip
        # else:
        #     ips = ['http://icanhazip.com/', 'http://ip.jsontest.com', 'https://ident.me']
        #     url = random.choices(ips)
        #     req = requests.get(url='https://ifconfig.me/ip', headers=dataUpload.header)
        #     if req.status_code == 200:
        #         logging.info(f'node wan ip is :> {req.text.strip()}')
        #         return req.text.strip()
        #     else:
        #         logging.error('node wan ip get error!')
        #         return ''



    def initArgs(self):
        self.ip = self.getWanIP()

        if self.args.localData == 'true':
            self.args.apiAddress = 'http://43.139.118.204:10101/api/upload_data'

        if os.path.exists(self.args.template) and self.args.resetConf == 'false':
            logging.info('1,load exist config file wg.conf..')
            f = open(self.args.template, 'r')
            self.runConf = json.load(f)
            f.close()
        else:
            logging.info('2,create default config file wg.conf..')
            if os.path.exists(self.args.template):
                os.remove(self.args.template)
            os.mknod(self.args.template)
            self.runConf = {'interval': self.args.interval,
                            'dataPath': self.args.dataPath,
                            'apiAddress': self.args.apiAddress
                            }
            with open(self.args.template, 'w') as f:
                json.dump(self.runConf, f)
                f.close()

    def read_data(self):
        datas = ''
        logging.info('get wg-easy name...')
        cmd = 'docker ps |grep -P "[\s]wg-easy*" -o'

        wg = os.popen(cmd)
        wgname = wg.readline()
        # for r in wg.readlines():
        #     wgname = wgname + r

        self.wgName = re.sub('\s|\t|\n','',wgname)
        logging.info('get wg-easy name is=>'+self.wgName)
        res = os.popen(f'docker exec -i {self.wgName} /bin/bash -c wg show ')
        for r in res.readlines():
            datas = datas + r
        with open(self.data_path,'w',encoding='utf-8') as f:
            f.write(datas)
            f.close()
        logging.info(f'wg show data save to {self.args.dataPath}')

    def get_data(self):
        logging.info('read wg show data...')
        clientip = []
        latest = []
        transfer = []
        self.sendData['datas'] =[]
        file = open(self.data_path, "r")
        for line in file:
            nline = line.strip().replace('/n', '')
            if "endpoint" in nline:
                clientip.append(nline)
            if "latest" in nline:
                latest.append(nline)
            if "transfer" in nline:
                transfer.append(nline)
        file.close()
        for i, d in enumerate(clientip):
            info = {"nodeIp":self.ip,"clientIP": d, "transfer": transfer[i], "conntime": latest[i]}
            self.sendData['datas'].append(info)
        logging.info('read wg show data done...')
        logging.info(self.sendData)

    def post_data(self):
        postdata ={}
        logging.info('post data ....')
        if self.args.localData == 'true':
            postdata = json.dumps({'datas':'local-data-test'})
            print('local data upload sucess')
            logging.info('local data upload sucess')
            logging.info('   end    ')
            return
        else:
            postdata = json.dumps(self.sendData)
            if not self.sendData['datas']:
                logging.info('--------------')
                logging.info('   get data is null,cancel upload')
                logging.info('--------------')
                logging.info('  end  ')
                logging.info('')
                return

        logging.info(f'uploal data-> {postdata}')

        try:
            req= requests.post(self.args.apiAddress, json=postdata, headers=self.header)
            print('status-code>',req.status_code)
            if req.status_code == 200:
                times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                logging.info(f'the data upload success>:{times}')
            else:
                logging.error('upload date error.')
        except Exception as e:
            logging.error('upload error,errcode-> ',e)
        logging.info('')
        logging.info('==========================================  end  ==================================================')
    def start(self):
        t = self.args.interval
        while True:
            t = t - 1
            sleep(1)
            if t <= 0:
                self.read_data()
                self.get_data()
                self.post_data()
                t = self.args.interval
            # print(t)

    def getEth(self):
        cmd = 'ip link|grep eth0 |wc -l'
        res = ''
        wg = os.popen(cmd)
        if int(wg.readline())>0:
            return 'eth0'
        else:
            return 'ens33'
    def addTimerTask(self):
        cmd = "crontab -r"
        os.popen(cmd)
        cmd = 'crontab -l | { cat; echo "*/2 * * * * ./' + self.args.scriptName + '" ; } | crontab -'
        os.popen(cmd)
        os.popen(f'touch {self.args.scriptName}')
        os.popen(f'chmod +x {self.args.scriptName}')
        logging.info('add timerTask cron done.')

    def createScript(self):
        strlist = [
            "#!/bin/bash",
            "COUNT=$(ps -ef |grep dataParse |grep -v grep |wc -l)",
            "if [ $COUNT -eq 0 ]; then",
            "  echo 'dataParse is not run,start...'>>./wg.log",
            "  ./dataParse --resetConf='true' & exit",
            "else",
            "  echo 'dataParse is runing....'>>./wg.log"
            "  exit",
            "fi"
        ]
        with open(self.args.scriptName,'w') as f:
            for line in strlist:
                f.writelines(line+'\n')
            f.close()
        logging.info('script create done.')


if __name__ == '__main__':
    dataUpload = DataUpload()
    # dataUpload.createScript()
    # dataUpload.addTimerTask()
    dataUpload.initArgs()
    # dataUpload.start()
    # dataUpload.addTimerTask()
    # dataUpload.createScript()







